package com.lmt.ymcc.comsumer;

import com.alibaba.fastjson.JSON;
import com.lmt.ymcc.constant.MessageConstant;
import com.lmt.ymcc.domain.MessageStation;
import com.lmt.ymcc.dto.StationMessageSend2MQ;
import com.lmt.ymcc.exception.GlobalException;
import com.lmt.ymcc.service.IMessageStationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Component
@RocketMQMessageListener(consumerGroup = "service-common-stationmessage-consumer",
        topic = MessageConstant.COURSE_MESSAGE_TOPIC,
        selectorExpression = MessageConstant.COURSE_MESSAGE_TAG_STATION
)
@Slf4j
public class StationMessageMQConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageStationService messageStationService;

    @Override
    public void onMessage(MessageExt message) {

        try {
            String bodyStr = new String(message.getBody(),"utf-8");
            StationMessageSend2MQ vo = JSON.parseObject(bodyStr, StationMessageSend2MQ.class);
           //1.保持数据到数据库
            MessageStation messageStation = new MessageStation();
            BeanUtils.copyProperties(vo, messageStation);
            messageStationService.insert(messageStation);
            log.info("站内信发送了");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobalException("站内信保存失败");
        }
    }
}